package api

import (
	"fmt"

	"gitee.com/hexug/devcloud/mcenter/apps"
	"gitee.com/hexug/devcloud/mcenter/apps/token"
	restfulspec "github.com/emicklei/go-restful-openapi/v2"
	"github.com/emicklei/go-restful/v3"
)

var _ apps.HttpObj = (*ApiServer)(nil)

type ApiServer struct {
	svc token.Server
}

func (a *ApiServer) Init() error {
	a.svc = apps.GetApp(token.AppName).(token.Server)
	if a.svc == nil {
		return fmt.Errorf("app %s 获取失败,疑似尚未注册", token.AppName)
	}
	return nil
}
func (a *ApiServer) Name() string {
	return token.AppName
}

func (a *ApiServer) Version() string {
	return "v1"
}
func (a *ApiServer) ReagisterRoute(r *restful.WebService) {
	tags := []string{"token"}
	//颁发令牌
	// http://127.0.0.1:2345/mcenter/api/v1/tokens post
	r.Route(r.POST("/").To(a.IssueToken).
		Doc("颁发令牌").
		Metadata(restfulspec.KeyOpenAPITags, tags).
		Metadata("auth", false).
		Param(r.BodyParameter("grant_type", "令牌类型").DataType("int").DefaultValue("0").Description("密码类型的令牌")).
		Param(r.BodyParameter("username", "用户名").DataType("string")).
		Param(r.BodyParameter("password", "密码").DataType("string")).
		Reads(token.IssueTokenRequest{}).
		Writes(token.Token{}).
		Returns(200, "OK", token.Token{}))
	//校验令牌
	// http://127.0.0.1:2345/mcenter/api/v1/tokens/{username} post
	r.Route(r.POST("/{username}").To(a.ValidateToken).
		Doc("校验令牌").
		Metadata(restfulspec.KeyOpenAPITags, tags).
		Metadata("auth", true).
		Param(r.PathParameter("username", "用户名").DataType("string")).
		Param(r.BodyParameter("access_token", "令牌").DataType("string")).
		Reads(token.ValidateTokenRequest{}).
		Writes(token.Token{}).
		Returns(200, "OK", token.Token{}))
	//删除令牌
	// http://127.0.0.1:2345/mcenter/api/v1/tokens delete
	r.Route(r.DELETE("/").To(a.DeleteToken).
		Doc("删除令牌").
		Metadata(restfulspec.KeyOpenAPITags, tags).
		Metadata("auth", true).
		Param(r.BodyParameter("grant_type", "令牌类型").DataType("int32").DefaultValue("0").Description("密码类型的令牌")).
		Param(r.BodyParameter("username", "用户名").DataType("string")).
		Param(r.BodyParameter("access_token", "令牌").DataType("string")).
		Reads(token.DeleteTokenRequest{}).
		Writes(token.Token{}).
		Returns(200, "OK", token.Token{}))
}

func init() {
	apps.RegisterHttp(&ApiServer{})
}
